package com.atguigu.case1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {
    private String connectString="192.168.80.130:2181,192.168.80.131:2181,192.168.80.132:2181";
    private Integer sessionTimeout=2000;
    private ZooKeeper zk;
    public static void main(String[] args) throws Exception {
        DistributeClient dc=new DistributeClient();
        //1.获取zk连接
        dc.getconnect(dc);
        //2、监听“/servers”下面子节点的增加和删除
        dc.getServerList();
        //3、业务逻辑（sleep）
        dc.business();

    }
    private void getconnect(DistributeClient dc) throws IOException {
        //1、获取zk连接
        zk=new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    dc.getServerList();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (KeeperException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void getServerList() throws InterruptedException, KeeperException {
        //2、监听“/servers”下面子节点的增加和删除
        List<String> children = zk.getChildren("/servers", true);
        List<String> value=new ArrayList<>();
        for (String child:children){
            byte[] data = zk.getData("/servers/" + child, false, null);
            value.add(new String(data));
        }
        System.out.println(value);
    }
    public void business() throws InterruptedException {
        //3、启动业务（sleep）
        Thread.sleep(1000000);
    }
}
